//
//  QianliUserRegisterVC.swift
//  todoios
//
//  Created by qianli on 2025/5/23.
//

import Foundation
import SwiftyUserDefaults

class QianliUserRegisterVC: QianliParentNaviVC {
    private var cWTPhgOUvVenvUrY: InputMailView?
    private var XObbAmti41Z1DqGB: InputMailView?
    private var viVV4GQEwb5QJDfC: InputPasswordView?
    private var X0jbaHEHHc6ZbaCb: InputMailView?
    private var tSDTdfTJsO37dEQz:UIButton?
    private var _countdown:Int = 60
    
    private var F8MC1HIDRYWx1xED:UIButton?
    private var MuZcwhmSPZFwNth9: GradientBtn?
    private var I7BYrTsbtcwOqtkG:UIImageView?
    private var mMj5rlMV98SudqQ4:Timer?
    
    private var _rg_mail:String=""
    private var _rg_pw:String=""
    
    var registerOKBlock: ((_ mail:String,_ pw:String) -> Void)?
    var doLoginBlock: os_block_t?
    
    override func GHL4Rhb91XYBer27() {
        self.zdMpsGrNncVEHdYA(title: LocalizedString("REGISTER"))
        let logoView = UIImageView(frame: CGRect(x: qianli_pm_width/2 - 80/2, y: topSpace+15, width: 80, height: 80))
        view.addSubview(logoView)
        logoView.image = "qianli_logo_main".qianli_R_image
        
        var iTop = topSpace+15+80+30
        
        self.cWTPhgOUvVenvUrY = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60) , icoName: "qianli_field_email", placeholder: LocalizedString("Please enter a email"), showclear: true)
        if let inputmail = self.cWTPhgOUvVenvUrY{
            view.addSubview(inputmail)
            inputmail.backgroundColor = .systemBackground
            inputmail.layer.cornerRadius = 30
            inputmail.DdITqvtW560pCIVj(type: .emailAddress)
        }
        iTop+=60+15
        self.XObbAmti41Z1DqGB = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70-90, height: 60) , icoName: "qianli_field_code", placeholder: LocalizedString("Please enter e-code"), showclear: false)
        if let inputcode = self.XObbAmti41Z1DqGB{
            view.addSubview(inputcode)
            inputcode.backgroundColor = .systemBackground
//            inputcode.layer.cornerRadius = 30
            inputcode.qianli_round_rect(corner: [.topLeft,.bottomLeft], radii: CGSize(width: 30, height: 30))
        }
        self.tSDTdfTJsO37dEQz = UIButton(frame: CGRect(x: qianli_pm_width-35-100, y: iTop, width: 100, height: 60))
        if let btnCode = self.tSDTdfTJsO37dEQz{
            view.addSubview(btnCode)
            btnCode.setTitle(LocalizedString("GET CODE"), for: .normal)
            btnCode.setTitleColor(.systemBlue, for: .normal)
            btnCode.backgroundColor = .systemBackground
//            btnCode.layer.cornerRadius = 30
            btnCode.qianli_round_rect(corner: [.topRight,.bottomRight], radii: CGSize(width: 30, height: 30))
            btnCode.titleLabel?.font = .systemFont(ofSize: 13)
            btnCode.touch_With_Block { [weak self] sender in
                self?.Vsp15DYMJGKZwKUn()
            }
        }
        iTop+=60+15
        self.viVV4GQEwb5QJDfC = InputPasswordView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60),placeholder: LocalizedString("Enter 4-digit password"))
        if let inputpw = self.viVV4GQEwb5QJDfC{
            view.addSubview(inputpw)
            inputpw.backgroundColor = .systemBackground
            inputpw.layer.cornerRadius = 30
        }
        iTop+=60+15
        self.X0jbaHEHHc6ZbaCb = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60) , icoName: "qianli_field_invitation", placeholder: LocalizedString("Invitation Code (Optional)"), showclear: false)
        if let inputvite = self.X0jbaHEHHc6ZbaCb{
           view.addSubview(inputvite)
            inputvite.backgroundColor = .systemBackground
            inputvite.layer.cornerRadius = 30
        }
        
        iTop+=60+20
        self.F8MC1HIDRYWx1xED = UIButton(type: .custom)
        if let radioBtn = self.F8MC1HIDRYWx1xED{
            radioBtn.setImage("qianli_checkbox_n".qianli_R_image, for: .normal)
            radioBtn.setImage("qianli_checkbox_h".qianli_R_image, for: .selected)
            radioBtn.frame = CGRect(x: 50, y: iTop+5, width: 20, height: 20)
            radioBtn.isSelected = false
            radioBtn.contentMode = .center
            view.addSubview(radioBtn)
            radioBtn.touch_With_Block { [weak self] sender in
                QianliVibrateEnum.light.vibrate()
                sender.isSelected = !sender.isSelected
                self?.view.endEditing(true)
            }
        }
        
        let textView = UITextView(frame: CGRect(x: 50+20+5, y: iTop, width: qianli_pm_width-35-24-10, height: 30))
        textView.isEditable = false
        textView.isSelectable = true //为true才能触发点击链接
        textView.delegate = self
        textView.font = .systemFont(ofSize: 13)
        textView.backgroundColor = .clear
        view.addSubview(textView)
        
        let msg = LocalizedString("SERVICE AGREEMENT & PRIVACY POLICY") //"已阅读并同意《用户服务协议》及《隐私政策》"
        let paragraphStyle = NSMutableParagraphStyle()
        let myMutableString = NSMutableAttributedString(
                    string: msg,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13),
                                 NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                 NSAttributedString.Key.foregroundColor:UIColor.label])
        let range_1:NSRange = (msg as NSString).range(of:LocalizedString("SERVICE AGREEMENT"))
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userProtocol") as Any], range: range_1)
        
        let range_2:NSRange = (msg as NSString).range(of:LocalizedString("PRIVACY POLICY"))
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userPrivate") as Any], range: range_2)
        textView.attributedText = myMutableString
        
        iTop+=30+30
        self.MuZcwhmSPZFwNth9 = GradientBtn(frame: CGRect(x: 40, y: iTop, width: qianli_pm_width-80, height: 48), title: LocalizedString("REGISTER Now"))
        if let registbtn = self.MuZcwhmSPZFwNth9{
            view.addSubview(registbtn)
            registbtn.touch_With_Block { [weak self] sender in
                self?.ph2lqG56246k5nHN()
            }
        }
        
        iTop+=48+20
        let loginBtn = UIButton(frame: CGRect(x: qianli_pm_width/2-120/2, y: iTop, width: 120, height: 20))
        view.addSubview(loginBtn)
        loginBtn.setTitle(LocalizedString("MAIL LOGIN"), for: .normal)
        loginBtn.setTitleColor(.secondaryLabel, for: .normal)
        loginBtn.titleLabel?.font = .systemFont(ofSize: 14)
        loginBtn.touch_With_Block { [weak self]sender in
            self?.UWRdl1krZEkBno2y()
        }
        
        iTop+=20+50
        let kefuBtn = UIButton(frame: CGRect(x: qianli_pm_width/2-60, y: iTop, width: 120, height: 20))
        view.addSubview(kefuBtn)
        kefuBtn.setTitle(LocalizedString("LINK US"), for: .normal)
        kefuBtn.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        kefuBtn.titleLabel?.font = .systemFont(ofSize: 13)
        kefuBtn.touch_With_Block { sender in
            let customUrl = Defaults[\.customerURL]
            QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
            }
        }
    }
}

extension QianliUserRegisterVC{
    private func UWRdl1krZEkBno2y(){
        view.endEditing(true)
        self.clFi25NuDNbscWXL()
        if (self.doLoginBlock != nil){
            doLoginBlock?()
        }
    }
    
    private func ph2lqG56246k5nHN(){
        view.endEditing(true)
        
        guard let btnRegister = self.MuZcwhmSPZFwNth9 else{//,btnRegister.tag != 10
            return
        }
        
        guard let inputmail = self.cWTPhgOUvVenvUrY,let inputpw = self.viVV4GQEwb5QJDfC,let inputcode = self.XObbAmti41Z1DqGB,let inputinvite = self.X0jbaHEHHc6ZbaCb else{
            return
        }
        
        let s_mail = inputmail.JRrMFFk8vXgbNlUN()
        if s_mail.isEmpty || !isValidEmail(s_mail){
            self.view.Qianli_Toast(LocalizedString("Please enter a valid email"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        let s_pw = inputpw.JRrMFFk8vXgbNlUN()
        if s_pw.isEmpty || s_pw.count<4{
            self.view.Qianli_Toast(LocalizedString("Please enter a valid password"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        
        let s_code = inputcode.JRrMFFk8vXgbNlUN()
        if s_code.isEmpty || s_pw.count<4{
            self.view.Qianli_Toast(LocalizedString("Please enter email code"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        
        let s_invite = inputinvite.JRrMFFk8vXgbNlUN()
        
        if let btnSelect = self.F8MC1HIDRYWx1xED{
            if !btnSelect.isSelected{
                view.Qianli_Toast(LocalizedString("Please read and agree to our Terms of Service & Privacy Policy."))
                QianliVibrateEnum.oldSchool.vibrate()
                return
            }
        }
   
        _rg_mail = s_mail
        _rg_pw = s_pw
        if let img = self.I7BYrTsbtcwOqtkG{
            img.removeFromSuperview()
            self.I7BYrTsbtcwOqtkG = nil
        }

        btnRegister.setTitle(LocalizedString("Registering..."), for: .normal)
        self.I7BYrTsbtcwOqtkG = UIImageView(frame: CGRect(x: btnRegister.bounds.width/2-90, y: btnRegister.bounds.height/2-18, width: 36, height: 36))
        if let img = self.I7BYrTsbtcwOqtkG{
            btnRegister.addSubview(img)
            img.qianli_image(imgurl: "qianliLoading.gif")
        }
//        btnRegister.tag = 10 //说明在注册中
        btnRegister.isEnabled = false
        
        let deviceid = getDeviceID()
        let request = RegisterRequest(device_id: deviceid, email_code: s_code, password: s_pw, re_password: s_pw, referrer_code: s_invite, user_name: s_mail)
        LoginViewModel.shared.kfXgRj1Y1WIRI1m7(registerRequest: request) {result in
            DispatchQueue.main.async {[weak self] in
                switch result {
                case .failure(let error):
                    self?.nZBulqJQR6iKWrn9("\(LocalizedString("Register Failed"))：\(error.localizedDescription)")
                    self?.suat6jfKq3gBu4Gg("Register.Failed:\(error.localizedDescription)")
                case .success(let registerResult):
                    if registerResult.code == 0{
                        self?.nZBulqJQR6iKWrn9("")
                    }else{
                        self?.nZBulqJQR6iKWrn9(registerResult.msg)
                    }
                }
            }
        }
    }
    
    private func nZBulqJQR6iKWrn9(_ msg:String){
        if let img = self.I7BYrTsbtcwOqtkG{
            img.removeFromSuperview()
        }
        if let btnRegister = self.MuZcwhmSPZFwNth9{
            btnRegister.isEnabled = true
            btnRegister.setTitle(LocalizedString("REGISTER Now"), for: .normal)
        }
        
        if(msg.isEmpty){
            self.registerOKBlock?(_rg_mail,"")
            self.clFi25NuDNbscWXL()
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
    
    private func Vsp15DYMJGKZwKUn(){
        self.view.endEditing(true)
        
        guard let inputmail = self.cWTPhgOUvVenvUrY else{
            return
        }
        let s_mail = inputmail.JRrMFFk8vXgbNlUN()
        if s_mail.isEmpty || !isValidEmail(s_mail){
            self.view.Qianli_Toast(LocalizedString("Please enter a valid email"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        if let btn = self.tSDTdfTJsO37dEQz{
            btn.isEnabled = false
        }
    
        // email_type可选值："EMAIL_TYPE_USER_REGISTER" "EMAIL_TYPE_USER_RESETPWD" "EMAIL_TYPE_TEST"
        let emailRequest = EmailCodeRequest(email_type: "EMAIL_TYPE_USER_REGISTER", target_email: s_mail)
        LoginViewModel.shared.ogOuZmnc3tTKZf96(emailCodeRequest: emailRequest){result in
            DispatchQueue.main.async {[weak self] in
                switch (result){
                case .success(let data):
                    if data.code == 0{
                        self?.h2TxvkkqORtyv725("")
                    }else{
                        self?.h2TxvkkqORtyv725(data.msg)
                    }
                case .failure(let error):
                    self?.h2TxvkkqORtyv725("\(LocalizedString("Get email code failed"))：\(error.localizedDescription)")
                }
            }
        }
    }
    
    private func h2TxvkkqORtyv725(_ errMsg:String){
        if errMsg.isEmpty{
            self.view.Qianli_Toast(LocalizedString("An email code has sent,please checkout!"))
            //开始倒计时
            vYwwyLv2Lsx8oZ39()
        }else{
            //关闭倒计时
            self.view.Qianli_Toast(errMsg)
            if let btn = self.tSDTdfTJsO37dEQz{
                btn.isEnabled = true
            }
        }
    }
    
    private func vYwwyLv2Lsx8oZ39(){
        if let btn = self.tSDTdfTJsO37dEQz{
            btn.isEnabled = false
        }
        Vsxa9l8jUKigDSiL()
        
        self.mMj5rlMV98SudqQ4 = Timer(timeInterval: 1, repeats: true, block: {[weak self] _ in
            if let self = self{
//                DispatchQueue.main.async { //任务可能因为诸如滚动UI时延迟执行，但不会中断
                    self._countdown -= 1
                    if self._countdown <= 0{
                        self.Vsxa9l8jUKigDSiL()
                    }else{
                        if let btn = self.tSDTdfTJsO37dEQz{
                            btn.setTitle("\(self._countdown)", for: .normal)
                        }
                    }
                }
//            }
        })
        if let timer = self.mMj5rlMV98SudqQ4{
            RunLoop.main.add(timer, forMode: .common) //确保在滚动等操作时 Timer 不中断
            timer.fire()
        }
    }
    
    private func Vsxa9l8jUKigDSiL(){
        if let timer = self.mMj5rlMV98SudqQ4{
            timer.invalidate()
        }
        self.mMj5rlMV98SudqQ4 = nil
        if let btn = self.tSDTdfTJsO37dEQz{
            btn.isEnabled = true
            btn.setTitle(LocalizedString("GET CODE"), for: .normal)
        }
        
        _countdown = 60
    }
}

extension QianliUserRegisterVC:UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "action://userProtocol" {
            GX2Ex29xLYziOn3d()
            return false
        }else if URL.absoluteString == "action://userPrivate" {
            A5emqwsTzcFhVbln()
            return false
        }
        return true
    }
    
    private func GX2Ex29xLYziOn3d(){
        QianliVibrateEnum.selection.vibrate()
        if let url = URL(string: "https://help.qianli999.com/service-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: LocalizedString("SERVICE AGREEMENT"))
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
    }
    
    private func A5emqwsTzcFhVbln(){
        QianliVibrateEnum.selection.vibrate()
        if let url = URL(string: "https://help.qianli999.com/privacy-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: LocalizedString("PRIVACY POLICY"))
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
    }
}
